package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SaleListGoodsDao;
import com.atguigu.jxc.entity.GoodVo;
import com.atguigu.jxc.entity.SaleDataVo;
import com.atguigu.jxc.service.SaleListGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.SaleListGoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SaleListGoodsService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SaleListGoodsServiceImpl implements SaleListGoodsService {
    @Autowired
    SaleListGoodsDao saleListGoodsDao;

    @Autowired
    private LogService logService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public void updateState(Integer saleListId) {
        this.saleListGoodsDao.updateState(saleListId);
    }

    @Override
    public List<GoodVo> count(String sTime, String eTime, Integer goodsTypeId, String codeOrName) {
        return saleListGoodsDao.count(sTime, eTime, goodsTypeId, codeOrName);
    }

    @Override
    public List<SaleDataVo> getSaleDataByDay(String sTime, String eTime) {
        List<SaleDataVo> purchaseDataByDay = saleListGoodsDao.getPurchaseDataByDay(sTime, eTime);
        HashMap<String, SaleDataVo> result = new HashMap<>();
        if (!CollectionUtils.isEmpty(purchaseDataByDay)) {
            purchaseDataByDay.forEach(saleDataVo -> {
                double profit = -saleDataVo.getPurchasingTotal();
                saleDataVo.setProfit(profit);
                result.put(saleDataVo.getDate(), saleDataVo);
            });
        }
        List<SaleDataVo> saleDataByDay = saleListGoodsDao.getSaleDataByDay(sTime, eTime);
        if (!CollectionUtils.isEmpty(saleDataByDay)) {
           saleDataByDay.forEach(saleDataVo -> {
               if (result.containsKey(saleDataVo.getDate())) {
                   SaleDataVo oldKey = result.get(saleDataVo.getDate());
                   saleDataVo.setPurchasingTotal(oldKey.getPurchasingTotal());
                   saleDataVo.setProfit(saleDataVo.getSaleTotal() - saleDataVo.getPurchasingTotal());
               }else
                   saleDataVo.setProfit(saleDataVo.getSaleTotal());
               result.put(saleDataVo.getDate(), saleDataVo);
           });
        }
            result.forEach((k,v)->{
                System.out.println(k);
            });

        return new ArrayList<>(result.values());
    }

    @Override
    public List<SaleDataVo> getSaleDataByMonth(String sTime, String eTime) {
        List<SaleDataVo> purchaseDataByMonth = saleListGoodsDao.getPurchaseDataByMonth(sTime, eTime);
        Map<String, SaleDataVo> result = new HashMap<>();
        if (!CollectionUtils.isEmpty(purchaseDataByMonth)) {
            purchaseDataByMonth.forEach(saleDataVo -> {
                double profit = -saleDataVo.getPurchasingTotal();
                saleDataVo.setProfit(profit);
                result.put(saleDataVo.getDate(), saleDataVo);
            });
        }
        List<SaleDataVo> saleDataByMonth = this.saleListGoodsDao.getSaleDataByMonth(sTime, eTime);
        if (!CollectionUtils.isEmpty(saleDataByMonth)) {
            saleDataByMonth.forEach(saleDataVo -> {
                if (result.containsKey(saleDataVo.getDate())) {
                    SaleDataVo oldResult = result.get(saleDataVo.getDate());
                    saleDataVo.setPurchasingTotal(oldResult.getPurchasingTotal());
                    saleDataVo.setProfit(saleDataVo.getSaleTotal() - saleDataVo.getPurchasingTotal());

                } else {
                    saleDataVo.setProfit(saleDataVo.getSaleTotal());
                    result.put(saleDataVo.getDate(), saleDataVo);
                }

            });
        }

        return new ArrayList<>(result.values());
    }

    @Override
    public Map<String, Object> list(String saleNumber, Integer customerId, Integer state, String sTime, String eTime) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            List<SaleList> saleListList = saleListGoodsDao.getsaleList(saleNumber, customerId, state, sTime, eTime);
            logService.save(new Log(Log.SELECT_ACTION, "销售单据查询"));
            result.put("rows", saleListList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Map<String, Object> goodsList(Integer saleListId) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            List<SaleListGoods> saleListGoodsList = saleListGoodsDao.getSaleListGoodsBySaleListId(saleListId);
            logService.save(new Log(Log.SELECT_ACTION, "销售单商品信息查询"));
            result.put("rows", saleListGoodsList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public ServiceVO delete(Integer saleListId) {
        saleListGoodsDao.deleteSaleListGoodsBySaleListId(saleListId);
        saleListGoodsDao.deleteBySaleListId(saleListId);
        //logService.save(new Log(Log.DELETE_ACTION, "确定删除吗?"));
        return new ServiceVO(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO save(SaleList saleList, String saleListGoodsStr) {
        // 使用谷歌Gson将JSON字符串数组转换成具体的集合
        Gson gson = new Gson();

        List<SaleListGoods> saleListGoodsList = gson.fromJson(saleListGoodsStr,new TypeToken<List<SaleListGoods>>(){}.getType());

        // 设置当前操作用户
        User currentUser = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());

        saleList.setUserId(currentUser.getUserId());

        // 保存销售单据信息
        saleListGoodsDao.saveSaleList(saleList);

        // 保存销售单商品信息
        for(SaleListGoods saleListGoods : saleListGoodsList){

            saleListGoods.setSaleListId(saleList.getSaleListId());

            saleListGoodsDao.saveSaleListGoods(saleListGoods);

            // 修改商品库存，状态
            Goods goods = goodsDao.findByGoodsId(saleListGoods.getGoodsId());

            goods.setInventoryQuantity(goods.getInventoryQuantity()-saleListGoods.getGoodsNum());

            goods.setState(2);

            goodsDao.updateGoods(goods);

        }

        // 保存日志
        //logService.save(new Log(Log.INSERT_ACTION, "新增商品报损单："+damageList.getDamageNumber()));

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}

